﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL_Class;
using System.Collections;
using System.IO;
using System.Threading;

namespace NLLSite.Administrator.UserControl
{
    public partial class ManageStudent : System.Web.UI.UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                for (int month = 1; month <= 13; month++)
                {
                    ddlMonth.Items.Add(new ListItem(month.ToString(), month.ToString()));
                }
                for (int year = 1900; year <= 2030; year++)
                {
                    ddlYear.Items.Add(new ListItem(year.ToString(), year.ToString()));
                }
                ddlMonth.SelectedValue = DateTime.Now.Month.ToString();
                ddlYear.SelectedValue = DateTime.Now.Year.ToString();

                for (int day = 1; day <= DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedItem.Value), Convert.ToInt32(ddlMonth.SelectedItem.Value)); day++)
                {
                    ddlDay.Items.Add(new ListItem(day.ToString(), day.ToString()));
                }
            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Panel1.Visible = false;
            Panel2.Visible = true;
            Session["CheckInID"] = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString();
            txtName.Text = GridView1.SelectedRow.Cells[2].Text;
            txtPhone.Text = GridView1.SelectedRow.Cells[3].Text;
             
            DateTime birthDay = Convert.ToDateTime(((Label)GridView1.SelectedRow.FindControl("lblDOB")).Text);
            ddlDay.SelectedValue = birthDay.Day.ToString();
            ddlMonth.SelectedValue = birthDay.Month.ToString();
            ddlYear.SelectedValue = birthDay.Year.ToString();
            txtEmail.Text = GridView1.SelectedRow.Cells[5].Text;
            txtCompany.Text = ((Label)GridView1.SelectedRow.FindControl("lblCompany")).Text;
            txtNote.Text = ((Label)GridView1.SelectedRow.FindControl("lblNote")).Text;
        }

        protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
        {
            HocVien hv = new HocVien();
            int RegisterID = Int32.Parse(((Label)GridView2.SelectedRow.FindControl("lblIDRegCourse")).Text);
            hv.DeleteRegisterCourse(RegisterID);
            GridView2.DataBind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            HocVien db = new HocVien();
            foreach (GridViewRow row in GridView1.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("cbxDelete");
                if (cb != null && cb.Checked)
                {
                    db.deleteCheckIn(Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString()));
                }
            }
            GridView1.DataBind();
        }

        protected void cbxCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("cbxDelete");
                if (cbxCheckAll.Checked)
                {
                    cb.Checked = true;
                }
                else
                {
                    cb.Checked = false;
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            HocVien hv = new HocVien();
            CheckIn CI = new CheckIn();
            CI.ID = Int32.Parse(Session["CheckInID"].ToString());
            CI.FullName = txtName.Text;
            CI.Phone = txtPhone.Text;
            CI.Email = txtEmail.Text;
            CI.DateOfBirth = Convert.ToDateTime((ddlYear.SelectedItem.Value + "-" + ddlMonth.SelectedItem.Value + "-" + ddlDay.SelectedItem.Value));
            CI.Company = txtCompany.Text;
            CI.Note = "";
            if(txtNote.Text != "")
            CI.Note = txtNote.Text;
            hv.updateCheckIn(CI);
            GridView1.DataBind();
            Panel1.Visible = true;
            Panel2.Visible = false;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Panel1.Visible = true;
            Panel2.Visible = false;
        }

        protected void txtPrint_Click(object sender, EventArgs e)
        {
            NLLDataContext db = new NLLDataContext();

            
                try
                {
                    string path = Server.MapPath("~/")+"thongtin.txt";
                    Response.Write(path);

                    string info = string.Empty;
                    StreamWriter sw = null;

                    //kiem tra su ton tai cua file
                    //Neu file da ton tai ghi tiep
                    if (File.Exists(path))
                    {
                        try
                        {
                            sw = File.AppendText(path);
                            sw.WriteLine("");
                            sw.WriteLine("*********************");
                            sw.WriteLine(DateTime.Now.ToString());
                            sw.WriteLine("*********************");
                            foreach (GridViewRow row in GridView1.Rows)
                            {
                                CheckBox cb = (CheckBox)row.FindControl("cbxDelete");
                                if (cb != null && cb.Checked)
                                {
                                    var objCheckIn = from p in db.CheckIns
                                                     where p.ID.Equals(Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString()))
                                                     select p;

                                    foreach (var item in objCheckIn)
                                    {
                                        info = item.FullName + ", phone: " + item.Phone + ", ngày sinh: " + item.DateOfBirth.ToString("dd-MM-yyyy") + ", email: " + item.Email + ", công ty: " + item.Company + ", thông tin thêm: " + item.Note;
                                        sw.WriteLine("");
                                        sw.WriteLine(info);
                                    }
                                }
                            }
                            sw.Flush();
                            sw.Close();
                            lblError.Visible = false;
                           
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }

                    //File ko ton tai thi tao moi 
                    else
                    {
                        try
                        {
                            sw = File.CreateText(path);
                            sw.WriteLine("");
                            sw.WriteLine("*********************");
                            sw.WriteLine(DateTime.Now.ToString());
                            sw.WriteLine("*********************");
                            foreach (GridViewRow row in GridView1.Rows)
                            {
                                CheckBox cb = (CheckBox)row.FindControl("cbxDelete");
                                if (cb != null && cb.Checked)
                                {
                                    var objCheckIn = from p in db.CheckIns
                                                     where p.ID.Equals(Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString()))
                                                     select p;

                                    foreach (var item in objCheckIn)
                                    {
                                        info = item.FullName + ", phone: " + item.Phone + ", ngày sinh: " + item.DateOfBirth.ToString("dd-MM-yyyy") + ", email: " + item.Email + ", công ty: " + item.Company + ", thông tin thêm: " + item.Note;
                                        sw.WriteLine("");
                                        sw.WriteLine(info);
                                    }

                                }
                            }
                            sw.Flush();
                            sw.Close();
                            lblError.Visible = false;
                            
                        }
                        catch (Exception ex)
                        {
                            lblError.Visible = true;
                            //lblError.Text = "Lỗi đường dẫn";
                            lblError.Text = ex.ToString();

                        }
                    }
                    string filename = "thongtin.txt";
                   // string FileFullPath = "FilesUpload/files/" + Request.QueryString["ebook"];
                    fileDownload(filename, Server.MapPath("~/" + filename));

                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    //lblError.Text = "Lỗi đường dẫn";
                    lblError.Text = ex.ToString();
                }
            
        }
        
        private void fileDownload(string fileName, string fileUrl)
        {
            Page.Response.Clear();
            bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
            if (!success)
                Response.Write("Downloading Error!");
            Page.Response.End();

        }
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    int pack = 10240; //10K bytes
                    int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int day = 1; day <= DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedItem.Value), Convert.ToInt32(ddlMonth.SelectedItem.Value)); day++)
            {
                ddlDay.Items.Add(new ListItem(day.ToString(), day.ToString()));
            }
        }

        protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int day = 1; day <= DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedItem.Value), Convert.ToInt32(ddlMonth.SelectedItem.Value)); day++)
            {
                ddlDay.Items.Add(new ListItem(day.ToString(), day.ToString()));
            }
        }
    }
}